$m(function(args) {
	var $this =  $(this.element).closest("body");
	var jobName = args.id;
	
	/**
	 * 下载任务日志
	 */
	var downloadLog = function(id, log, name, runResult){
		TempoUtils.downLoadFile({
			url: contextPath + "/api/ai/mine/publish/downloadJobLog",
			data : {
				id : id,
				name : name,
				log : log,
				runResult : runResult
			}
		});
	}
	//绑定事件
	var bindJobGridEvent = function() {
		var grid = $this.find("#mine-opt-task-grid");
		grid.find(".viewlog").each(function(){
			var rowid = $(this).attr('rowid');
			var row = null;
			var rows = grid.data('rows');
			if(rows && rows.length > 0){
				for (var m = 0; m < rows.length; m++) {
					if(rowid == rows[m].id){
						row = rows[m];
					}
				}
			}
			var logs = [row];
			var content;
			if(logs && logs.length > 0){
				var logele = $('<ul>').css({
					'list-style-type' : 'none'
				});
				for (var i = 0; i < logs.length; i++) {
					var log = logs[i];
					var date = new Date(parseFloat(log.runTime));
					var runResult = log.runResult;
					var icon = "ui-icon ui-icon-document";
					if (runResult != null) {
						if (runResult == 0) {
							icon = "ui-icon tempo-ui-icon tempo-ui-icon-no-mutual tempo-ui-icon-red-circle-errorprompt";
						} else if (runResult == 1) {
							icon = "ui-icon tempo-ui-icon tempo-ui-icon-no-mutual tempo-ui-icon-red-circle-check-thin";
						}
					}
					var logName = DateUtils.formatDateTime(date, 'yyyy-MM-dd HH:mm:ss')
					var liele = $('<li class="logitem">').attr('jobid', log.jobName).attr('logid', log.id).attr('runResult', log.runResult).attr('name', logName);
					var liicon = $("<span>").addClass(icon).appendTo(liele);
					var lilabel = $("<label>").text(logName).appendTo(liele);
					logele.append(liele);
				}
				content = $('<div>').append(logele).html();
			}
			var height = 'auto';
			if(logs && logs.length > 0 && logs.length > 5){
				height = 100;
			} else if(logs && logs.length > 0 && logs.length <= 5) {
				height = logs.length * 20;
			}
			$(this).webuiPopover({
				trigger : 'hover',
				title : '',
				cache : false,
				placement : 'left',
				width : 195,
				height: height,
				closeable : false,
				arrow : true,
				content : content
			});
			$(this).on('shown.webui.popover', function(){
				$('.logitem').each(function(index, domEle){
					$(domEle).off('click').on('click',function(){
						var jobid = $(this).attr('jobid');
						var logid = $(this).attr('logid');
						var runResult = $(this).attr('runResult');
						var name = $(this).attr('name');
						downloadLog(jobid, logid, name, runResult);
					})
				});
			});
		});
		
	}
	
	var initGrid = function() {
		var grid = $this.find("#mine-opt-task-grid").datagrid({
			datatype : "json",
			url : contextPath + '/api/ai/mine/publish/listTask?jobName=' + jobName,
			postData : {},
			fit:true,
			rownumbers : true,
			mtype : 'POST',
			rowNum:10,
			rownumbers : true,
			shrinkToFit : true, 
			viewrecords : true,
			striped : true,
			colNames : ['id', 
			            "执行时间",
			            "执行耗时(s)",
			            "执行结果",
			            "操作"
			          ],
			colModel:[{
				name : 'id',
				index : 'id',
				hidden : true
			},{
				name : 'excuteTime',
				index : 'excuteTime',
				align : 'center',
				resizable:false,
				sortable : false
			},{
				name : 'costTime',
				index : 'costTime',
				align : 'center',
				resizable:false,
				sortable : false,
				formatter : function(obj, grid, rows, state) {
					if(obj == "0.0") {
						return "--";
					} else{
						return obj;
					}
					
				}
			},{
				name : 'runResult',
				index : 'runResult',
				align : 'center',
				resizable:false,
				sortable : false,
				formatter : function(obj, grid, rows, state) {
					if(obj == 0) {
						return "<span style='color:red'>"+
						TempoUtils
						.locale("mine.shibai")
						+ "</span>";
					} else if(obj == 1) {
						return "<span style='color:#0d7edd'>"+
						TempoUtils
						.locale("mine.chenggong")
						+ "</span>";
					}
					return "--";
				}
			},{
				sortable : false,
				align : 'center',
				width : 70,
				buttons:[{
					id : "loginsight",
					icon:"ui-icon tempo-ui-icon tempo-ui-icon-mode-insight",
					title: "日志",
					click:function(e,dt){	     
						logInsight(dt.rowData);
					}
				},{
					id : "kill",
					icon:"ui-icon tempo-ui-icon tempo-ui-icon-kill",
					title: "停止当前任务",
					click:function(e,dt){	     
						stopJob(dt.rowData);
					}
				}]
			}],
			loadComplete : function(datas){
				var rows = datas.rows;
				if (rows && rows.length > 0) {
					for (var i = 0; i < rows.length; i++) {
						var row = rows[i];
						var id = row.id;
						var runResult = row.runResult;
						if (runResult == 0 || runResult == 1) {
							grid.find("#"+id).find(".tempo-ui-icon-kill").hide();
						} else {
							
						}
					}
				}
				$(this).data('rows', rows);
				bindJobGridEvent();
				if($this.find("mscript").length > 0){
					$this.find("#mine-opt-task-grid").parent().parent().css("height", window.outerHeight - 270);
				}
			},
			pagination : true
		});
	}
	
	/**
	 * 停止任务
	 */
	var stopJob = function(data) {
		var progressbar = $("<div/>").tempoprogressbar();
		$.ajax({
			url : contextPath + '/api/ai/app/schedule/job/stop',
			type : 'post',
			data : {
				id : data.jobName, 
				triggerId : data.trigid,
				logId: data.id
			},
			dataType:'json',
			success : function(obj) {
				progressbar.tempoprogressbar("destroy");
				var grid = $this.find("#mine-opt-task-grid");
				if (obj.success) {
					$("<div/>").alert({msg :  TempoUtils.locale("mine.publish-job-killed"), height : 180});
					grid.find("#"+data.id).find(".tempo-ui-icon-kill").hide();
					//后台任务状态监控线程每隔3000ms监控一次，改变执行状态，所以这块先根据调用成功状态前台将状态重置，然后隔3s重新加载列表，其实这个列表应该是定时3s刷新的
					setTimeout(function(){
						grid.datagrid("reloadGrid");
					}, 3000);
				} else {
					$("<div/>").alert({msg :  TempoUtils.locale("mine.publish-job-notexists"), height : 180});
				}
			}
		});
	}
	
	var getDownLoadBtn = function() {
		return $("<button class='downAll' style='background: #f8fafd;height:28px;border: 1px solid #D7DDE5;width:110px;padding-right: 10px;padding-left: 10px;font-size: 13px;margin-bottom: 5px;'>"+TempoUtils.locale("mine.downlog")+"</button>").button({
			icon:"ui-icon tempo-ui-icon tempo-ui-icon-no-mutual tempo-ui-icon-mine-download"
		});
	}
	
	var logInsight = function(log) {
		var interval = null;
		var logDialog = $("<div></div>").appendTo('body');
		logDialog.window({
			width : 950,
			height: 550,
			title: "日志详情",
			modal:true,
			allowMax: true,
			resizable: true,
			close:function(){
				if (interval != null) {
					window.clearInterval(interval);
				}
				logDialog.window("destroy").remove();
			},
			maximized: function(event) {
				console.log('window maximized');
			},
			open:function() {
				var date = new Date(parseFloat(log.runTime));
				var logName = DateUtils.formatDateTime(date, 'yyyy-MM-dd HH:mm:ss')
				var runResult = log.runResult;
				var jobName = log.jobName;
				var logid = log.id;
				var downLoadBtn = getDownLoadBtn();
				downLoadBtn.unbind("click").bind("click",function(e){
					downloadLog(jobName, logid, logName, runResult);
				});
				$("<div style=''></div>").append(downLoadBtn).appendTo(logDialog);
				var taskLogDiv = $("<div class='task-log-detail'></div>").appendTo(logDialog);
				if (log.runResult != -1) {
					$.ajax({
						url:contextPath+"/api/ai/mine/publish/getJobLog",
						data : {
							id : jobName,
							log : logid,
							linenumber:"-1"
						},
						dataType:'json',
						type:'post',
						success:function(result){
							if (result.status) {
								var datas = result.data;
								taskLogDiv.empty();
								for (var i = 0; i < datas.length; i++) {
									$("<p>"+TempoMineUtils.encodeHTML(datas[i]) + "</p>").appendTo(taskLogDiv);
								}
							}
						},
						error:function(){
						}
					});
				} else {
					var linenumber = "-1";
					interval = setInterval(function(){
						$.ajax({
							url:contextPath+"/api/ai/mine/publish/getJobLog",
							data : {
								id : jobName,
								log : logid,
								linenumber:linenumber
							},
							dataType:'json',
							type:'post',
							success:function(result){
								if (result.status) {
									var datas = result.data;
									taskLogDiv.empty();
									for (var i = 0; i < datas.length; i++) {
										$("<p>"+TempoMineUtils.encodeHTML(datas[i]) + "</p>").appendTo(taskLogDiv);
									}
									var scrollHeight = taskLogDiv.prop("scrollHeight");
									taskLogDiv.scrollTop(scrollHeight,200);
									linenumber = result.linenumber;
								}
							},
							error:function(){
							}
						});
					},1000);
				}
		
			},
			buttons:[{
				text:'关闭',
				click:function(){
					if (interval != null) {
						window.clearInterval(interval);
					}
					logDialog.window("close");
				}
			}]
		});
	}
	
	var initTaskSearch = function() {
		var grid = $this.find("#mine-opt-task-grid");
		var form = $this.find("#queryTaskForm").css("display","block");
		TempoUtils.parserUi(form,{});
		form.find('[name="starttime"]').validatebox({readonly:true, validator: true}).datepicker({
			dateFormat : "yy-mm-dd",
			yearRange: "c-100:",
			//设置日期的最大时间和最小时间
			minDate : DateUtils.formatDate(new Date(new Date().getFullYear() - 100, 0, 1)),
			maxDate : DateUtils.formatDate(new Date(new Date().getFullYear(), 11, 31)),
			changeYear:true,
			changeMonth:true,
			onClose: function( selectedDate ) {
				var d = $(this).datepicker('getDate');
				if(d == null){
					return;
				}
				var d2 = new Date(d.getTime());
				var d2str = d2.Format('yyyy-MM-dd');
				form.find('[name="endtime"]').datepicker( "option", "minDate", d2str );
			},
			onSelect: function(value){
			},
			onChangeMonthYear : function(year, month, inst){ 
				var month = inst.selectedMonth + 1;
				var day = inst.selectedDay;
				var format = function(v) { return String(v).length > 1 ? v : ('0' + v) }
				$(this).val(inst.selectedYear + '-' + format(month) + '-' + format(inst.selectedDay));
				$.datepicker._hideDatepicker(this);
			}
		});
		form.find('[name="endtime"]').validatebox({readonly:true, validator: true}).datepicker({
			dateFormat : "yy-mm-dd",
			yearRange: "c-100:",
			//设置日期的最大时间和最小时间
			minDate : DateUtils.formatDate(new Date(new Date().getFullYear() - 100, 0, 1)),
			maxDate : DateUtils.formatDate(new Date(new Date().getFullYear() , 11, 31)),
			changeYear:true,
			changeMonth:true,
			onSelect: function(value){
			},
			onClose: function( selectedDate ) {
				var d = $(this).datepicker('getDate');
				if(d == null){
					return;
				}
				var d2 = new Date(d.getTime());
				var d2str = d2.Format('yyyy-MM-dd');
				form.find('[name="starttime"]').datepicker( "option", "maxDate", d2str );
			},
			onChangeMonthYear : function(year, month, inst){ 
				var month = inst.selectedMonth + 1;
				var day = inst.selectedDay;
				var format = function(v) { return String(v).length > 1 ? v : ('0' + v) }
				$(this).val(inst.selectedYear + '-' + format(month) + '-' + format(inst.selectedDay));
				$.datepicker._hideDatepicker(this);
			}
		});
		
		form.find('.queryBtn').button({
			emphasize:true,
			click:function(e){
				var starttime = form.find('[name="starttime"]').datepicker('getDate');
				var endtime = form.find('[name="endtime"]').datepicker('getDate');
				var status = form.find('[name="excutestatus"]').val();
				var minCostTime = form.find('[name="minCostTime"]').val();
				var maxCostTime = form.find('[name="maxCostTime"]').val();
				var data = {
						starttime: starttime ? DateUtils.formatDate(starttime, 'yyyy-MM-dd') : null,
						endtime: endtime ? DateUtils.formatDate(endtime, 'yyyy-MM-dd') :null,
						status: status,
						minCostTime:minCostTime,
						maxCostTime:maxCostTime,
						page:1
				}
				grid.datagrid("reloadGridToLastPage", data, true, true, 1);
				e.preventDefault();
		}});
		
		form.find('.resetBtn').button({
			emphasize:true,
			click : function(e){
				form[0].reset();
				form.find('[name="endtime"]').datepicker( "option", "minDate", DateUtils.formatDate(new Date(new Date().getFullYear() - 100, 0, 1)) );
				form.find('[name="starttime"]').datepicker( "option", "maxDate", DateUtils.formatDate(new Date(new Date().getFullYear() , 11, 31)) );
				form.find('[name="excutestatus"]').val('').selectmenu('refresh');
				form.find('[name="minCostTime"]').val('');
				form.find('[name="maxCostTime"]').val('');
				e.preventDefault();
		}});

		var resize = function () {
			if(window.innerWidth < 1200) {
				form.find('[name=starttime],[name=endtime]').width(80);
				form.find('[name=minCostTime],[name=maxCostTime]').width(70);
				form.find('[name=excutestatus]').next().width(60);
			} else {
				form.find('[name=starttime],[name=endtime]').width(110);
				form.find('[name=minCostTime],[name=maxCostTime]').width(110);
				form.find('[name=excutestatus]').next().width(120);
			}
		}
		resize();
	}
	initTaskSearch();
	initGrid()
});